package com.duanjw.springcloud.oss;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

/**
 * 文件工具类
 *
 * @author duanjw
 */
@Slf4j
@UtilityClass
public class FileUtil {
    /**
     * IE 内核
     */
    private static final String[] IE_CORE = new String[]{"MSIE","Trident"};
    /**
     * 浏览器代理
     */
    public static final String USER_AGENT = "User-Agent";
    /**
     * POSTMAN内核
     */
    public static final String POSTMAN_CORE = "PostmanRuntime";

    /**
     * 流的方式下载文件
     * @param request
     * @param response
     * @param inputStream
     * @param filename
     */
    @SneakyThrows
    public void download(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String filename) {
        // 文件名编码，解决中文文件名乱码
        filename = encodeFilename(request, filename);
        // 清空response
        response.reset();
        response.setCharacterEncoding("utf-8");
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("application/octet-stream");
        IoUtil.copy(inputStream, response.getOutputStream());
    }

    /**
     * 文件名编码，解决中文文件名乱码
     * @param request
     * @param filename
     * @return
     */
    @SneakyThrows
    public String encodeFilename(HttpServletRequest request, String filename) {
        String userAgent = request.getHeader(USER_AGENT);
        // 针对IE或者以IE为内核的浏览器，postman也需要编码，但是编码后还是乱码，不编码下载的文件不对
        if (StrUtil.containsAnyIgnoreCase(userAgent, IE_CORE) || userAgent.contains(POSTMAN_CORE)) {
            filename = java.net.URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
        } else {
            // 非IE浏览器的处理：
            filename = URLEncoder.createDefault().encode(filename, StandardCharsets.UTF_8);
        }
        return filename;
    }
}
